package com.dn.lotte.ui.usercenter.activity;

import android.graphics.Bitmap;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dn.lotte.R;
import com.dn.lotte.api.ServerApi;
import com.dn.lotte.api.UserCenterServerApi;
import com.dn.lotte.app.GlobalApplication;
import com.dn.lotte.app.HttpURL;
import com.dn.lotte.bean.EventBusBean;
import com.dn.lotte.bean.MemberBankBean;
import com.dn.lotte.bean.SetSafequesBean;
import com.dn.lotte.bean.Vipbean;
import com.dn.lotte.utils.focuedsTextview;
import com.dn.lotte.widget.ClearEditText;
import com.easy.common.base.BaseActivity;
import com.easy.common.commonutils.StringUtils;
import com.easy.common.commonwidget.DnToolbar;
import com.easy.common.commonwidget.RippleView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.popup.QMUIListPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 提现
 * Created by ASUS on 2017/10/10.
 */

public class WithdrawalActivity extends BaseActivity implements RippleView.OnRippleCompleteListener {
    @Bind(R.id.lt_main_title_left)
    TextView ltMainTitleLeft;
    @Bind(R.id.lt_main_title)
    TextView ltMainTitle;
    @Bind(R.id.lt_main_title_right)
    TextView ltMainTitleRight;
    @Bind(R.id.toolbar)
    DnToolbar toolbar;
    @Bind(R.id.tv_yumoney)
    TextView tvYumoney;
    @Bind(R.id.tv_withdrawle)
    TextView tvWithdrawle;
    @Bind(R.id.tv_withdrawle_bank)
    TextView tvWithdrawleBank;
    @Bind(R.id.rl_withdrawal_bank)
    RelativeLayout rlWithdrawalBank;
    @Bind(R.id.tv_bund)
    TextView tvBund;
    @Bind(R.id.tv_bund_card)
    TextView tvBundCard;
    @Bind(R.id.rl_bund_card)
    RelativeLayout rlBundCard;
    @Bind(R.id.tv_withdrawle_name)
    TextView tvWithdrawleName;
    @Bind(R.id.tv_adress)
    focuedsTextview tvAdress;
    @Bind(R.id.rl_adress)
    RelativeLayout rlAdress;
    @Bind(R.id.tv_withdrawle_money)
    TextView tvWithdrawleMoney;
    @Bind(R.id.et_money)
    EditText etMoney;
    @Bind(R.id.tv_psw)
    TextView tvPsw;
    @Bind(R.id.et_password)
    EditText etPassword;
    @Bind(R.id.okBtn)
    RippleView okBtn;
    @Bind(R.id.uncode)
    TextView uncode;
    @Bind(R.id.et_code)
    ClearEditText etCode;
    @Bind(R.id.codeImg)
    ImageView codeImg;
    @Bind(R.id.iv_shuaxin)
    ImageView ivShuaxin;
    private List<MemberBankBean.TableBean> mbanklist = new ArrayList<>();
    private PopupWindow window;
    private String bankid;
    private Animation operatingAnim;
    private QMUIListPopup mListPopup;

    @Override
    public int getLayoutId() {
        return R.layout.activity_withdrawal;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        initTitle();
        toolbar.setToolbarLeftBackImageRes(R.drawable.icon_back);
        toolbar.setMainTitle(R.string.usercenter_withdrawal);
        okBtn.setOnRippleCompleteListener(this);
        if (GlobalApplication.getInstance().getUserModel().getTable().get(0).getIstruename().equals("0")) {
            showPopTrueName();
        }

        initOther();
    }

    private void initOther() {
        operatingAnim = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_refesh);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        tvYumoney.setText(GlobalApplication.getInstance().getUserModel().getTable().get(0).getMoney());
        getMemberBank();
        initCodeImage();
    }

    //获取验证码
    private void initCodeImage() {
        //获取验证码
        OkGo.<Bitmap>get(HttpURL.Base_Url + "/plus/getcode.aspx")
                .execute(new BitmapCallback() {
                    @Override
                    public void onSuccess(Response<Bitmap> response) {
                        codeImg.setImageBitmap(response.body());
                    }
                });
    }

    @OnClick({R.id.iv_shuaxin, R.id.codeImg, R.id.rl_withdrawal_bank})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_shuaxin:
                if (operatingAnim != null) {
                    ivShuaxin.startAnimation(operatingAnim);
                    getMemberMsgUrl();
                }
                break;
            case R.id.rl_withdrawal_bank:
                if (mbanklist.size() == 0) {
                    showShortToast("你还没有绑定银行卡");
                } else {
                    initListPopupIfNeed();
                    mListPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_LEFT);
                    mListPopup.setPreferredDirection(QMUIPopup.DIRECTION_BOTTOM);
                    mListPopup.show(view);
                }
                break;
            case R.id.codeImg:
                initCodeImage();
                break;
        }
    }

    //充值方式
    private void initListPopupIfNeed() {
        if (mListPopup == null) {
            List<String> mylist = new ArrayList<>();
            for (MemberBankBean.TableBean bean : mbanklist) {
                mylist.add(bean.getPaybank());
            }
            ArrayAdapter adapter = new ArrayAdapter<>(mContext, R.layout.simple_list_item, mylist);
            mListPopup = new QMUIListPopup(mContext, QMUIPopup.DIRECTION_NONE, adapter);
            mListPopup.create(QMUIDisplayHelper.dp2px(mContext, 200), QMUIDisplayHelper.dp2px(mContext, 220), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    tvWithdrawleBank.setText(mbanklist.get(i).getPaybank());
                    tvBundCard.setText(mbanklist.get(i).getPayaccount());
                    tvWithdrawleName.setText(mbanklist.get(i).getPayname());
                    tvAdress.setText(mbanklist.get(i).getPaybankaddress());
                    bankid = mbanklist.get(i).getId();
                    mListPopup.dismiss();
                }
            });
            mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        }
    }

    //会员银行
    public void getMemberBank() {
        UserCenterServerApi.getMemberBank()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MemberBankBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull MemberBankBean memberBankBean) {
                        stopProgressDialog();
                        if (memberBankBean.getResult().equals("1")) {
                            mbanklist = memberBankBean.getTable();
                        } else {
                            showShortToast(memberBankBean.getReturnval());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();
                    }
                });
    }

    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.okBtn:
                if (GlobalApplication.getInstance().getUserModel().getTable().get(0).getIstruename().equals("0")) {
                    showPopTrueName();
                } else {
                    String money = etMoney.getText().toString().trim();
                    String code = etCode.getText().toString().trim();
                    String psw = etPassword.getText().toString().trim();
                    String string = tvWithdrawleBank.getText().toString();
                    if (!string.equals("请选择提现银行")) {
                        if (!StringUtils.isEmpty(money)) {
                            if (!StringUtils.isEmpty(psw)) {
                                if (!StringUtils.isEmpty(code)) {
                                    HttpParams params = new HttpParams();
                                    params.put("userBankId", bankid);
                                    params.put("money", money);
                                    params.put("pass", psw);
                                    params.put("code", code);
                                    getWithdrawalUrl(params);
                                } else {
                                    showShortToast("请输入验证码");
                                }
                            } else {
                                showShortToast("请输入资金密码");
                            }
                        } else {
                            showShortToast("请输入金额");
                        }
                    } else {
                        showShortToast("请选择提现银行");
                    }
                    break;
                }
        }
    }
    //弹出绑定真是姓名对话框，强制绑定
    private void showPopTrueName() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(mContext);
        builder.setTitle("真实姓名没有绑定，请绑定!")
                .setPlaceholder("输入真实姓名")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        String text = builder.getEditText().getText().toString();
                        Log.i("DNLOG", text);
                        if (text != null && text.length() > 0) {
                            HttpParams params = new HttpParams();
                            params.put("name", text);
                            realNameUrl(params,text);
                            dialog.dismiss();
                        } else {
                            Toast.makeText(mContext, "请填入您的真实姓名", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .show();
    }
    private void realNameUrl(HttpParams params, final String name) {
        UserCenterServerApi.setRealname(params)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        stopProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SetSafequesBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull SetSafequesBean setSafequesBean) {
                        stopProgressDialog();
                        if (setSafequesBean.getResult().equals("1")){
                            GlobalApplication.getInstance().getUserModel().getTable().get(0).setTruename(name);
                            GlobalApplication.getInstance().getUserModel().getTable().get(0).setIstruename("1");
                        }
                        showShortToast(setSafequesBean.getReturnval());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();
                    }
                });

    }
    //提现
    public void getWithdrawalUrl(HttpParams params) {
        UserCenterServerApi.getbankMoney(params)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SetSafequesBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull SetSafequesBean setSafequesBean) {
                        stopProgressDialog();
                        if (setSafequesBean.getResult().equals("1")) {
                            finish();
                            EventBus.getDefault().post(new EventBusBean<String>("TiXianSuccess", "TiXianSuccess"));
                        }
                        showShortToast(setSafequesBean.getReturnval());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();

                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();

                    }
                });
    }

    public void getMemberMsgUrl() {
        ServerApi.getVipInfoData()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Vipbean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull Vipbean vipbean) {
                        stopProgressDialog();
                        GlobalApplication.getInstance().setUserModel(vipbean);
                        tvYumoney.setText(vipbean.getTable().get(0).getMoney());
                        ivShuaxin.clearAnimation();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                        ivShuaxin.clearAnimation();
                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();
                    }
                });
    }
}
